package api

import (
	"encoding/json"
	"strconv"
	"strings"
	"supershare/backend/middleware"
	"supershare/backend/models"
	"supershare/backend/utils"
	"time"

	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
)

// GroupBuyController 微信小程序团购接口
type GroupBuyController struct {
	web.Controller
}

// GetList 获取团购券列表
func (c *GroupBuyController) GetList() {

	admin, _ := middleware.GetCurrentAdmin(c.Ctx)
	if admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "没有权限",
		}
		c.ServeJSON()
		return
	}

	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	storeId, _ := c.GetInt64("storeId", 0)

	// 获取有效的团购活动
	activities, err := models.GetActiveGroupBuyActivities(storeId, admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购券列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 分页处理
	totalCount := len(activities)
	startIndex := (page - 1) * pageSize
	endIndex := startIndex + pageSize
	if endIndex > totalCount {
		endIndex = totalCount
	}

	var pagedActivities []interface{}
	if startIndex < totalCount {
		pagedActivities = make([]interface{}, endIndex-startIndex)
		for i, activity := range activities[startIndex:endIndex] {
			pagedActivities[i] = activity
		}
	} else {
		pagedActivities = make([]interface{}, 0)
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"list":  pagedActivities,
			"total": totalCount,
		},
	}
	c.ServeJSON()
}

// GetDetail 获取团购券详情
func (c *GroupBuyController) GetDetail() {
	// 获取团购券ID
	id, _ := strconv.ParseInt(c.GetString("id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 获取团购活动详情
	activity, err := models.GetGroupBuyActivityById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购券详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 如果活动已删除或已禁用，返回错误
	if activity.IsDeleted == 1 || activity.Status == 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该团购券不存在或已下架",
		}
		c.ServeJSON()
		return
	}

	// 获取关联的门店信息
	var storeNames []string
	var storeIDs []int64
	if err := json.Unmarshal([]byte(activity.ApplicableStores), &storeIDs); err == nil && len(storeIDs) > 0 {
		stores, err := models.GetStoresByIds(storeIDs)
		if err == nil {
			for _, store := range stores {
				storeNames = append(storeNames, store.Name)
			}
		}
	}
	storeName := strings.Join(storeNames, ", ")

	// 计算有效期天数
	validDays := int((activity.EndTime - activity.StartTime) / (24 * 60 * 60))
	if validDays <= 0 {
		validDays = 30 // 默认30天
	}

	// 检查是否已过期
	now := time.Now().Unix()
	if now > activity.EndTime {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该团购券已过期",
		}
		c.ServeJSON()
		return
	}

	// 转换为前端需要的格式
	detailData := map[string]interface{}{
		"id":                activity.Id,
		"name":              activity.Name,
		"image":             activity.Image,
		"originalPrice":     activity.OriginalPrice,
		"price":             activity.GroupPrice,
		"validDays":         validDays,
		"description":       activity.Description,
		"storeName":         storeName,
		"applicable_stores": storeIDs,
		"duration":          "使用期限以购买后显示为准",
		"timeRange":         "使用时间以具体门店营业时间为准",
		"storeRange":        storeName,
		"supportBalance":    false,
		"minMembers":        activity.MinMembers,
		"maxMembers":        activity.MaxMembers,
		"limitPerMember":    activity.LimitPerMember,
		"soldCount":         activity.SoldCount,
		"startTime":         activity.StartTime,
		"endTime":           activity.EndTime,
		"rules": []string{
			"1. 该团购券仅限在有效期内使用；",
			"2. 该团购券不可与其他优惠券同时使用；",
			"3. 该团购券可使用范围:仅限指定的门店可用,请注意查看",
		},
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取团购券详情成功",
		"data":    detailData,
	}
	c.ServeJSON()
}

// Buy 购买团购券
func (c *GroupBuyController) Buy() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析请求数据
	var requestData struct {
		ActivityId int64 `json:"activity_id"`
		Quantity   int   `json:"quantity"`
	}

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据",
		}
		c.ServeJSON()
		return
	}

	if requestData.ActivityId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "团购券ID无效",
		}
		c.ServeJSON()
		return
	}

	if requestData.Quantity <= 0 {
		requestData.Quantity = 1
	}

	// 获取团购活动详情
	activity, err := models.GetGroupBuyActivityById(requestData.ActivityId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购券信息失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 检查团购活动状态
	if activity.Status != 1 || activity.IsDeleted == 1 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该团购券已下架或不可用",
		}
		c.ServeJSON()
		return
	}

	// 检查活动有效期
	now := time.Now().Unix()
	if now < activity.StartTime || now > activity.EndTime {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该团购券不在可购买时间范围内",
		}
		c.ServeJSON()
		return
	}

	// 检查购买数量限制
	if activity.LimitPerMember > 0 {
		// 获取用户已购买的数量
		purchasedCount, err := models.GetMemberGroupBuyPurchasedCount(member.Id, activity.Id)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "检查购买限制失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		if purchasedCount+requestData.Quantity > activity.LimitPerMember {
			logs.Debug("purchasedCount: %d, requestData.Quantity: %d, activity.LimitPerMember: %d", purchasedCount, requestData.Quantity, activity.LimitPerMember)
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "超出每人购买数量限制",
			}
			c.ServeJSON()
			return
		}
	}

	// 创建订单
	orderNo := utils.GenerateOrderNo("GRP")
	amount := int64(float64(requestData.Quantity) * activity.GroupPrice)

	order := &models.GroupBuyOrder{
		OrderNo:      orderNo,
		ActivityId:   activity.Id,
		ActivityName: activity.Name,
		UserId:       member.Id,
		MemberId:     member.Id,
		Username:     member.Name,
		Phone:        member.Phone,
		Quantity:     requestData.Quantity,
		Amount:       amount,
		Status:       1, // 待支付
		GroupStatus:  1, // 待成团
	}

	// 创建支付参数 - 需要获取用户的openId
	// 从会员信息中获取openId，如果没有则使用空字符串
	openId := ""
	if member.OpenId != "" {
		openId = member.OpenId
	}

	payParams, err := utils.GenerateWxPayParams(member.FranchiseId, orderNo, int64(amount), "团购券购买-"+activity.Name, openId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "生成支付参数失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}
	// 使用基本模型的字段
	order.CreatedBy = member.Name
	order.CreatedAt = time.Now().Unix()

	// 保存订单
	orderId, err := models.CreateGroupBuyOrder(order)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}
	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建团购订单成功",
		"data": map[string]interface{}{
			"order_id":   orderId,
			"order_no":   orderNo,
			"pay_params": payParams,
		},
	}
	c.ServeJSON()
}

// GetMyGroupBuy 获取我的团购券列表
func (c *GroupBuyController) GetMyGroupBuy() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 50)
	status, _ := c.GetInt8("status", 0) // 0表示所有状态

	// 构建查询条件
	filters := map[string]interface{}{
		"user_id": member.Id,
	}

	// 如果指定了状态，添加状态过滤
	if status > 0 {
		filters["status"] = status
	} else {
		// 默认查询已支付的有效订单
		filters["status"] = models.GroupBuyOrderStatusPaid
	}

	// 获取订单列表
	orders, total, err := models.GetGroupBuyOrderList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取我的团购券失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 转换为前端需要的格式
	var result []map[string]interface{}
	for _, order := range orders {
		// 获取团购活动详情
		activity, err := models.GetGroupBuyActivityById(order.ActivityId)
		if err != nil {
			continue
		}

		// 计算有效期
		validUntil := order.PaidAt + 30*24*60*60 // 默认购买后30天有效
		if activity.EndTime > 0 {
			validUntil = activity.EndTime
		}

		// 当前时间
		now := time.Now().Unix()

		// 判断是否过期
		isExpired := now > validUntil

		// 添加到结果列表
		result = append(result, map[string]interface{}{
			"id":                 order.Id,
			"name":               activity.Name,
			"duration":           activity.DeductibleHours,
			"order_no":           order.OrderNo,
			"activity_id":        order.ActivityId,
			"quantity":           order.Quantity,
			"validDate":          time.Unix(validUntil, 0).Format("2006-01-02"),
			"valid_until":        validUntil,
			"create_time":        order.CreatedAt,
			"paid_at":            order.PaidAt,
			"status":             order.Status,
			"group_status":       order.GroupStatus,
			"is_expired":         isExpired,
			"description":        activity.Description,
			"applicable_stores":  activity.ApplicableStores,
			"applicable_venues":  activity.ApplicableVenues,
			"available_weekdays": activity.AvailableWeekdays,
			"available_times":    activity.AvailableTimes,
		})
	}

	// 返回数据
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取我的团购券成功",
		"data":    result,
		"total":   total,
		"page":    page,
		"size":    pageSize,
	}
	c.ServeJSON()
}

// GetUsageRange 获取团购券使用范围
func (c *GroupBuyController) GetUsageRange() {
	// 获取团购券ID
	id, _ := strconv.ParseInt(c.GetString("id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 获取团购活动详情
	activity, err := models.GetGroupBuyActivityById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购券信息失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 如果活动已删除或已禁用，返回错误
	if activity.IsDeleted == 1 || activity.Status == 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该团购券不存在或已下架",
		}
		c.ServeJSON()
		return
	}

	// 获取关联的门店信息
	var availableStores []map[string]interface{}
	var storeIDs []int64
	if err := json.Unmarshal([]byte(activity.ApplicableStores), &storeIDs); err == nil && len(storeIDs) > 0 {
		stores, err := models.GetStoresByIds(storeIDs)
		if err == nil {
			for _, store := range stores {
				availableStores = append(availableStores, map[string]interface{}{
					"id":      store.Id,
					"name":    store.Name,
					"address": store.Address,
					"phone":   store.Phone,
					"logo":    store.Logo,
				})
			}
		}
	}

	// 获取关联的场馆信息
	var availableVenues []map[string]interface{}
	var venueIDs []int64
	if err := json.Unmarshal([]byte(activity.ApplicableVenues), &venueIDs); err == nil && len(venueIDs) > 0 {
		venues, err := models.GetVenuesByIds(venueIDs)
		if err == nil {
			for _, venue := range venues {
				if venue.Status == 1 && venue.IsDeleted == 0 {
					availableVenues = append(availableVenues, map[string]interface{}{
						"id":          venue.Id,
						"name":        venue.Name,
						"description": venue.Description,
					})
				}
			}
		}
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取使用范围成功",
		"data": map[string]interface{}{
			"stores": availableStores,
			"venues": availableVenues,
		},
	}
	c.ServeJSON()
}
